<?php

require_once __DIR__ . '/../../vendor/autoload.php';

use JLPay\Core\OrgConfig;
use JLPay\Core\DemoConfig;
use JLPay\Services\Cashier\CashierService;
use JLPay\Models\Cashier\PreOrderRequest;
use JLPay\Utils\Logger;
use JLPay\Utils\DemoRequestHandler;

/**
 * 收银台 - 预下单功能使用示例
 */

// =================== 工具函数 =====================
/**
 * 创建配置对象
 */
function createConfig(): OrgConfig
{
    return DemoConfig::createConfig();
}

// =================== 数据构建函数 =====================
/**
 * 构建预下单请求
 */
function buildPreOrderRequest(): PreOrderRequest
{
    $request = new PreOrderRequest();
    
    // 设置请求参数
    $request->setMerchNo("849584358120018")
        ->setTermNo("60131234")
        ->setOutTradeNo("ld201911023465529")
        ->setPaymentValidTime("10")
        ->setDescription("充值中心-会员充值")
        ->setAttach("商城—-易拉宝10个打印纸20箱")
        ->setTotalAmount("1")
        ->setRemark("该订单物流请走顺丰快递")
        ->setNotifyUrl("https://help.jlpay.com/api/docs/home")
        ->setEnvVersion("release")
        ->setMerchAppid("wx336dcaf6a1ecf632")
        ->setReturnUrl("page/home/webview/webview?src=https%3A%2F%2Fmp.elong.com%2Ftenthousandaura%2F%3Factivitycode%3Dd32d7735-ae4f-440c-bb0c-dba4deba9470%26isSocket%3DHotelActivityId_8407&isRefresh=refresh&isSocket=HotelActivityId_8407**ecf632");
    
    return $request;
}

// =================== 示例函数 =====================
/**
 * 预下单示例
 */
function preOrderDemo(): void
{
    $logger = Logger::getInstance();
    $logger->info("开始执行预下单示例");
    
    // 创建配置对象和收银台服务
    $config = createConfig();
    $cashierService = new CashierService($config);
    
    // 创建预下单请求
    $request = buildPreOrderRequest();
    
    // 发送请求 - 使用DemoRequestHandler
    $response = DemoRequestHandler::sendRequestAndHandleResponse(
        $cashierService, 
        $request, 
        "预下单",
        function($service, $request) {
            return $service->createPreOrder($request);
        }
    );

    // 处理响应结果
    if ($response && $response->isSuccess()) {
        $logger->info("响应报文：" . json_encode($response->toArray(), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
    }
}

// =================== 主程序 =====================
if (php_sapi_name() === 'cli') {
    $logger = Logger::getInstance();
    
    // 设置日志级别为INFO
    $logger->setLevel('INFO');
    
    $logger->info(str_repeat("=", 50));
    $logger->info("===== 预下单示例 开始 =====");
    $logger->info(str_repeat("=", 50));
    preOrderDemo();
    $logger->info(str_repeat("=", 50));
    $logger->info("===== 预下单示例执行完毕 =====");
    $logger->info(str_repeat("=", 50));
} 